package com.hy.admin.security.service.impl;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.hy.admin.dao.AccountDao;
import com.hy.admin.dao.MemberDao;
import com.hy.admin.domain.dto.UserDto;
import com.hy.admin.domain.dto.UserFormDto;
import com.hy.admin.domain.dto.UserJsonDto;
import com.hy.admin.domain.dto.UserOverviewDto;
import com.hy.admin.domain.shared.security.HyUserDetails;
import com.hy.admin.domain.user.Privilege;
import com.hy.admin.domain.user.User;
import com.hy.admin.domain.user.UserRepository;
import com.hy.admin.entity.AccountEntity;
import com.hy.admin.entity.MemberEntity;
import com.hy.admin.enums.EnumAuditStatus;
import com.hy.admin.enums.EnumMemberType;
import com.hy.admin.security.config.CustomOAuth2Exception;
import com.hy.admin.security.service.UserService;
import com.hy.admin.security.service.business.CurrentUserJsonDtoLoader;
import com.hy.admin.security.service.business.UserFormSaver;

@Component
public class MyUserDetailService implements UserService{

	private Logger logger=LoggerFactory.getLogger(getClass());	

	@Autowired
    private UserRepository userRepository;
	
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private AccountDao accountDao;
	
	@Value("${admin.username}")
	private String adminUserName;
	
	@Value("${admin.passwd}")
	private String adminPasswd;
	
	protected static final GrantedAuthority ADMIN_ROLE = new SimpleGrantedAuthority("ROLE_" + Privilege.ADMIN.name());
	protected static final GrantedAuthority TEACHER_ROLE = new SimpleGrantedAuthority("ROLE_" + Privilege.TEACHER.name());
	protected static final GrantedAuthority WEIXIN_ROLE = new SimpleGrantedAuthority("ROLE_" + Privilege.WEIXIN.name());
	protected static final GrantedAuthority PARENT = new SimpleGrantedAuthority("ROLE_" + Privilege.PARENT.name());
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("登陆的用户名为："+username);
		String uname=StringUtils.substringBefore(username, "&");
		logger.info(uname);
		String loginType=StringUtils.substringAfter(username, "&");
		logger.info(loginType);
		
		 HyUserDetails userDetails=null;
	     
		 if("admin".equals(loginType)) {
			 if(this.adminUserName.equals(uname)) {
					userDetails=new HyUserDetails(ADMIN_ROLE);
					userDetails.setUsername(username);
					userDetails.setNotpassword(this.adminPasswd);
					userDetails.setPassword(DigestUtils.md5Hex(this.adminPasswd));
			}else {
				throw new UsernameNotFoundException("用户不存在");
			} 
		 }else {
		 	userDetails = new HyUserDetails(TEACHER_ROLE);
			 AccountEntity accountEntity = accountDao.selectByLoginName(uname);
			 if (accountEntity == null) {
				 throw new CustomOAuth2Exception("手机号未注册");
			 }
			 List<MemberEntity> memberEntityList = memberDao.selectByMobile(uname);
			 if (memberEntityList.isEmpty()) {
				 throw new UsernameNotFoundException("手机号未注册");
			 }
			 //如果用户为教师，判断教师审核状态，未审核或审核不通过，禁止登录
			 MemberEntity member = memberEntityList.get(0);
			 if (member != null && member.getMemberType() != null
					 && member.getMemberType() == EnumMemberType.Teacher.getId()
					 && member.getAuditStatus() != EnumAuditStatus.PASS.getId()) {

	//	            throw new UsernameNotFoundException("未通过审核");
				 throw new CustomOAuth2Exception("未通过审核");
			 }
			 if (member.getMemberType() == EnumMemberType.Teacher.getId()) {
				 userDetails = new HyUserDetails(TEACHER_ROLE);
			 } else {
				 userDetails = new HyUserDetails(PARENT);
			 }
			 //微信用户修改用户角色为 WEIXIN_ROLE
			 if("weixin".equals(loginType)) {
				 userDetails = new HyUserDetails(WEIXIN_ROLE);
			 }
	        userDetails.setUsername(username);
	        userDetails.setNotpassword(accountEntity.getPassword());
	        userDetails.setPassword(DigestUtils.md5Hex(accountEntity.getPassword()));
	        userDetails.setMemberEntity(memberEntityList.get(0));
		}
        return userDetails;
		
	}

	@Override
    public UserJsonDto loadCurrentUserJsonDto() {
        CurrentUserJsonDtoLoader dtoLoader = new CurrentUserJsonDtoLoader();
        return dtoLoader.load();
    }

    @Override
    public UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto) {
        List<User> users = userRepository.findUsersByUsername(overviewDto.getUsername());
        overviewDto.setUserDtos(UserDto.toDtos(users));
        return overviewDto;
    }

    @Override
    public boolean isExistedUsername(String username) {
        final User user = userRepository.findByUsername(username);
        return user != null;
    }

    @Override
    public String saveUser(UserFormDto formDto) {
        UserFormSaver saver = new UserFormSaver(formDto);
        return saver.save();
    }

}
